﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Expressions;
using DevFx.Model;

namespace DevFx.Web.Code
{
    public static class Order
    {
        public static IQueryable<T> DataSorting<T>(IQueryable<T> source, string ordering)
        {
            var type = typeof(T);
            var property = type.GetProperty(ordering);
            var parameter = Expression.Parameter(type, "c");
            var propertyAccess = Expression.MakeMemberAccess(parameter, property);
            var orderByExp = Expression.Lambda(propertyAccess, parameter);


            //Expression expr = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, property.PropertyType }, source.Expression, Expression.Lambda(Expression.Property(param, sortExpression), param));
            //IQueryable<T> query = source.AsQueryable().Provider.CreateQuery<T>(expr);

            MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, property.PropertyType }, source.Expression, orderByExp);
          //  return source.Provider.CreateQuery<T>(resultExp);
           IQueryable<T> query= source.AsQueryable().Provider.CreateQuery<T>(resultExp);
           return query;
        }
    }
}